/*
 * Copyright 2009 Johnson Consulting Services
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * 
 */
package com.johnsoncs.gwt.application.client.validation.constraints;

import static com.johnsoncs.gwt.application.client.validation.ValidationState.parameters;

import com.johnsoncs.gwt.application.client.validation.Constraint;
import com.johnsoncs.gwt.application.client.validation.ValidationContext;
import com.johnsoncs.gwt.application.client.validation.ValidationState;
import com.johnsoncs.gwt.application.client.validation.ValidationValue;
import com.johnsoncs.gwt.application.client.validation.ValidationState.Severity;
import com.johnsoncs.gwt.widgets.client.util.Callback;

/**
 * @author wilj
 *
 */
public class LengthConstraint implements Constraint {
	private final Integer minLength;
	private final Integer maxLength;

	/**
	 * @param minLength
	 * @param maxLength
	 */
	public LengthConstraint(final Integer minLength, final Integer maxLength) {
		super();
		this.minLength = minLength;
		this.maxLength = maxLength;
	}

	/* (non-Javadoc)
	 * @see com.johnsoncs.gwt.application.client.validation.Constraint#applyTo(com.johnsoncs.gwt.application.client.validation.ValidationValue, com.johnsoncs.gwt.application.client.validation.ValidationContext, com.johnsoncs.gwt.widgets.client.util.Callback)
	 */
	@Override
	public void applyTo(final ValidationValue value, final ValidationContext context,
			final Callback<ValidationState> callback) {
		final Object o = value.getValue();
		final String s = (o == null) ? "" : o.toString().trim();

		final int len = s.length();
		if (minLength != null && maxLength != null && (len < minLength || len > maxLength)) {
			callback.exec(new ValidationState("lengthOutOfRange", Severity.ERROR, value.getQueryPath(),
					parameters("minLength", minLength, "maxLength", maxLength)));

		} else if (minLength != null && len < minLength) {
			callback.exec(new ValidationState("minLength", Severity.ERROR, value.getQueryPath(),
					parameters("minLength", minLength)));

		} else if (maxLength != null && len > maxLength) {
			callback.exec(new ValidationState("outOfRange", Severity.ERROR, value.getQueryPath(),
					parameters("maxLength", maxLength)));
		} else {
			callback.exec(null);
		}
	}

}
